import config from '@/config';
import mockApi from '@/mock/api/game';

const request = async (url, options = {}) => {
  const { method = 'GET', data = null, headers = {} } = options;
  
  // 判断是否使用mock数据
  if (config.api.useMock) {
    const mockHandler = mockApi[`${method} ${url}`];
    if (mockHandler) {
      return new Promise((resolve) => {
        const mockResponse = {
          json: (data) => resolve(data),
          status: 200
        };
        mockHandler({ body: data }, mockResponse);
      });
    }
  }

  try {
    const response = await uni.request({
      url: `${config.api.baseUrl}${url}`,
      method,
      data,
      header: headers,
      timeout: config.api.timeout
    });
    
    if (response.statusCode >= 200 && response.statusCode < 300) {
      return response.data;
    } throw new Error(`请求失败：${response.statusCode}`);
  } catch (error) {
    console.error('API请求错误:', error);
    throw error;
  }
};

export default request;
